/**
 * 字典 util
 * author: xys
 * date: 20220209
 */

import { ajaxGetDictItems } from '@/services/dict'
import store from '@/store'

/**
 * 获取字典数组
 * @param dictCode 字典Code
 * @return List<Map>
 */
export async function initDictOptions(dictCode) {
  if (!dictCode) {
    return '字典Code不能为空!'
  }
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(dictCode)) {
    const res = {
      result: getDictItemsFromCache(dictCode),
      success: true
    }
    return res
  }
  // 获取字典数组
  const res = await ajaxGetDictItems(dictCode)
  setDictItemsFromCache(dictCode, res)
  return res
}

// 请求字典后缓存字典，以备之后使用
function setDictItemsFromCache(dictCode, res) {
  if (res.success) {
    store.commit('dict/setDict', { dictCode: dictCode, dictItems: res.result })
  }
}

/**
 * 字典值替换文本通用方法,根据字典options
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
export function filterDictText(dictOptions, text) {
  if (text != null && Array.isArray(dictOptions)) {
    const result = []
    // 允许多个逗号分隔，允许传数组对象
    let splitText
    if (Array.isArray(text)) {
      splitText = text
    } else {
      splitText = text.toString().trim().split(',')
    }
    for (const dictItem of dictOptions) {
      const value = dictItem.itemValue || dictItem.value
      if (splitText.includes(value.toString())) {
        const dictText = (dictItem.itemText || dictItem.label)
        result.push(dictText)
      }
    }
    return result.join(',')
  }
  return text
}

/**
 *  翻译字段值对应的文本,根据字典编码,该方法只取缓存内
 * @param children
 * @returns string
 */
export function filterDictTextByCache(dictCode, key) {
  if (key == null || key.length === 0) {
    return
  }
  if (!dictCode) {
    return '字典Code不能为空!'
  }
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(dictCode)) {
    const item = getDictItemsFromCache(dictCode).filter(t => t['itemValue'] === key)
    if (item && item.length > 0) {
      return item[0]['itemText'] || item[0]['label']
    }
  }
}

/** 通过code获取字典数组 */
export async function getDictItems(dictCode, params) {
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(dictCode)) {
    const desformDictItems = getDictItemsFromCache(dictCode).map(item => ({ ...item, label: item.itemText }))
    return desformDictItems
  }

  // 缓存中没有，就请求后台
  return await ajaxGetDictItems(dictCode, params).then(({ success, result }) => {
    if (success) {
      const res = result.map(item => ({ ...item, label: item.itemText }))
      setDictItemsFromCache(dictCode, res)
      return Promise.resolve(res.result.items)
    } else {
      console.error('getDictItems error: : ', result)
      return Promise.resolve([])
    }
  }).catch((res) => {
    console.error('getDictItems error: ', res)
    return Promise.resolve([])
  })
}

// 从缓存中获取字典配置
export function getDictItemsFromCache(dictCode) {
  const dictData = store.getters['dict/dictData']
  if (dictData && dictData[dictCode]) {
    return dictData[dictCode]
  }
  return false
}
